import scrapy

from ScrapyObject.spiders.utils.url_utils import *

'''
scrapy crawl ydam -o ydam.json
https://www.cztv1017.sbs/
'''


class YdamSpider(scrapy.Spider):
    name = "ydam"
    # 前缀
    prefix = 'https://www.'
    # 中缀
    website = 'cztv1017'
    # 后缀
    suffix = '.sbs/'
    allowed_domains = [website + '.sbs']
    start_urls = [prefix + website + suffix]

    def __init__(self):
        self.i = 0

    def parse(self, response):
        content = get_data(response)
        video_url = get_video_url_one(content)
        url = response.xpath("//a[@class='video-pic loading']/@ href").extract()
        name = response.xpath("//a[@class='video-pic loading']/@ title").extract()
        p_url = response.xpath("//a[@class='video-pic loading']//img/@ data-original").extract()
        tags = response.xpath("//a[@href='#']/text()").extract()
        if len(url) and len(p_url) and len(name):
            for i in range(len(url)):
                self.i = self.i + 1
                yield get_video_item(id=self.i, tags='', url=split_joint(self.prefix + self.website + self.suffix, url[i]), name=name[i], pUrl=split_joint(self.prefix + self.website + self.suffix, p_url[i]), vUrl='')
        if len(video_url) and len(tags):
            unique_list = list(set(video_url))
            self.i = self.i + 1
            yield get_video_item(id=self.i, tags=tags[-1].strip(), url=response.url, name='', pUrl='', vUrl=unique_list[-1])
        url_list = get_url(content)
        for url in url_list:
            if url.startswith('/') and url.endswith('.html'):
                yield scrapy.Request(split_joint(self.prefix + self.website + self.suffix, url), callback=self.parse)
